package com.mobilad.bean;

import java.io.Serializable;

import javax.annotation.Resource;
import javax.faces.application.ViewHandler;
import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.web.HttpRequestHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.request.FacesRequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.mobilad.service.*;
import com.sun.net.httpserver.HttpContext;

public class UserBean extends MasterBean implements Serializable    {
private static final long serialVersionUID = 1L;
	
	@Autowired
	private HttpServletRequest request;

	
	public String firstName;
	public String lastName;
	public String password;
	private String phExist;
	

	public String getPhExist() {
		return phExist;
	}


	public void setPhExist(String phExist) {
		this.phExist = phExist;
	}


	public String getPwd() {
		return pwd;
	}


	public void setPwd(String pwd) {
		this.pwd = pwd;
	}


	public String getMobNr() {
		return mobNr;
	}


	public void setMobNr(String mobNr) {
		this.mobNr = mobNr;
	}

	public String getLastName() {
		return lastName;
	}


	public void setLastName(String lastName) {
		this.lastName = lastName;
	}


	public String getFirstName() {
		return firstName;
	}


	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}


	public String getPassword() {
		return password;
	}


	public void setPassword(String password) {
		this.password = password;
	}

	 @RequestMapping(method = RequestMethod.POST)
	public String saveUser(){
		//First and last name connect
		String fullName = firstName+" " + lastName;
		actualUser.setUserName(fullName) ;
		actualUser.setEnabled(true) ;
		actualUser.setUserAuthority("ROLE_USER");
	
		if(!userService.isMobileNr(this.actualUser.getMobNr())){
			setPhExist("") ;
			boolean saveFlag = userService.saveUser(this.actualUser);
			if(saveFlag){
	//			request = (HttpServletRequest) FacesUtils.getExternalContext().getRequest();
	//			request = ((ServletRequestAttributes)requestAttributes).getRequest();
	//			HttpServletRequest curRequest =	((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();

				autoLogin(request, mobNr, pwd) ;
				clearUser();
				return "registered/user?faces-redirect=true";
			}else{
				return "";
			}
		}else{
			setPhExist("Phone Number Already Exist") ;
			return "";
		}
	}

	
	@Autowired
	 @Qualifier("org.springframework.security.authenticationManager")
	 protected AuthenticationManager authenticationManager;

	  public void autoLogin(HttpServletRequest request, String mobNr, String pwd) {
	    try {
	      // Must be called from request filtered by Spring Security, otherwise SecurityContextHolder is not updated
	      request.getSession();
	      UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(mobNr, pwd);
	      token.setDetails(new WebAuthenticationDetails(request));
	      Authentication authentication = authenticationManager.authenticate(token);
	      SecurityContextHolder.getContext().setAuthentication(authentication);
	    } catch (Exception e) {
	      SecurityContextHolder.getContext().setAuthentication(null);
	    }
	  }
	  
	 
	public String clearUser(){
		actualUser.setAddress("");
		actualUser.setCity("");
		actualUser.setEmailAddress("");
		actualUser.setMobModel("");
		actualUser.setMobModelNr("") ;
		actualUser.setMobNr("");
		actualUser.setPostalcode("");
		actualUser.setPwd("") ;
		actualUser.setUserName("");
		this.firstName="";
		this.lastName="";
		this.password="";
		this.loginFailMsg="";
		refreshPage();
		return "";
	}
	
	
	/**
	 * This code refresh the page
	 */
	private void refreshPage()
	{
		FacesContext context = FacesContext.getCurrentInstance();   
		String viewId = context.getViewRoot().getViewId();   
		ViewHandler handler = context.getApplication().getViewHandler();   
		UIViewRoot root = handler.createView(context, viewId);   
		root.setViewId(viewId);   
		context.setViewRoot(root);  		
	}
	
	
}
